package org.ns.learn.rpc.client;

import org.ns.learn.rpc.codec.RpcResponse;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class MessageCallback {

    private volatile RpcClientResponse response;
    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    private long requestTime; // 请求时间

    public MessageCallback(long requestTime) {
        this.requestTime = requestTime;
    }

    public void setResponse(RpcClientResponse response) {
        lock.lock();
        try {
            this.response = response;
            response.setRequestTime(requestTime); // 给应答设置请求时间
            response.setRespsonseTime(System.currentTimeMillis());
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public RpcClientResponse getResponse(int second) {
        lock.lock();
        try {
            condition.await(second, TimeUnit.SECONDS);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return response;
        } finally {
            lock.unlock();
        }
    }
}
